import time
import threading


class ReadWriteLock:
    def __init__(self):
        self._read_ready = threading.Condition(threading.Lock())
        self._readers = 0

    def acquire_read(self):
        with self._read_ready:
            while self._readers < 0:
                self._read_ready.wait()
            self._readers += 1

    def release_read(self):
        with self._read_ready:
            self._readers -= 1
            if not self._readers:
                self._read_ready.notifyAll()

    def acquire_write(self):
        with self._read_ready:
            while self._readers != 0:
                self._read_ready.wait()
            self._readers = -1

    def release_write(self):
        with self._read_ready:
            self._readers = 0
            self._read_ready.notifyAll()

# 使用示例


def reader(lock, num):
    lock.acquire_read()
    try:
        print(f"Reader-{num} starts reading.")
        time.sleep(1)
        print(f"Reader-{num} stops reading.")
    finally:
        lock.release_read()


def writer(lock, num):
    lock.acquire_write()
    try:
        print(f"Writer-{num} starts writing.")
        time.sleep(1)
        print(f"Writer-{num} stops writing.")
    finally:
        lock.release_write()


if __name__ == '__main__':
    rw_lock = ReadWriteLock()

    for i in range(2):
        threading.Thread(target=writer, args=(rw_lock, i)).start()
    for i in range(3):
        threading.Thread(target=reader, args=(rw_lock, i)).start()
